﻿using System.Text;

using Newtonsoft.Json;
using NLog;

namespace DbBackupAssist.Extensions
{
    public static class DbConfigurationManager
    {
        private readonly static ILogger _logger = LogManager.GetCurrentClassLogger();

        public static DbBackupConfiguration Load()
        {
            var backupConfiguration = new DbBackupConfiguration();

            try
            {
                var configFile = new FileInfo(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, $"Settings\\appSettings.json"));

                if (configFile.Exists)
                {
                    var content = File.ReadAllText(configFile.FullName);

                    backupConfiguration = JsonConvert.DeserializeObject<DbBackupConfiguration>(content, new JsonSerializerSettings
                    {
                        Formatting = Formatting.Indented,
                    });
                }
                else
                {
                    //如果配置文件夹不存在，则创建文件夹
                    if (!configFile.Directory.Exists)
                    {
                        configFile.Directory.Create();
                    }

                    //创建默认的配置文件
                    using var sw = new StreamWriter(configFile.FullName, false, Encoding.UTF8);
                    sw.Write(JsonConvert.SerializeObject(backupConfiguration, Formatting.Indented));
                }
            }
            catch (Exception ex)
            {
                _logger.Error(ex.Message);
                _logger.Error(ex.StackTrace);
            }

            return backupConfiguration;
        }

        public static void Save(this DbBackupConfiguration backupConfiguration)
        {
            try
            {
                var configFile = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, $"Settings\\appSettings.json");

                using var sw = new StreamWriter(configFile, false, Encoding.UTF8);
                sw.Write(JsonConvert.SerializeObject(backupConfiguration, Formatting.Indented));
            }
            catch (Exception ex)
            {
                _logger.Error(ex.Message);
            }
        }
    }
}
